<template>
  <div class="addContext">
    <h3 style="margin-left: 80px">{{ stuId ? "修改" : "新增" }}学生证</h3>
    <el-form :model="student" label-width="120px">
      <el-form-item label="学号">
        <el-input v-model="student.stuId"></el-input>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="student.name"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="student.sex" placeholder="请选择性别">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班级">
        <el-input v-model="student.stuClass"></el-input>
      </el-form-item>
      <el-form-item label="系部">
        <el-select v-model="student.category" placeholder="请选择系部">
          <el-option
            v-for="(item, index) in category"
            :key="index"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save(student)">{{
          stuId ? "修改" : "创建"
        }}</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop } from "vue-property-decorator";
import { State, Action } from "vuex-class";

@Component
export default class EditStudent extends Vue {
  @Prop(String) readonly stuId?: string;
  @State("studentList") studentList: any;
  @Action("addStu") add: any;
  @Action("editStu") edit: any;
  @Action("initStu") initStu: any;

  student: any = {};

  category = [
    "商学院",
    "土木与工程学院",
    "建筑与设计学院",
    "信息工程学院",
    "文理学院",
    "思想政治理论课教学部",
  ];

  created() {
    if (this.stuId) {
      this.fetch();
    }
  }

  async save() {
    try {
      if (this.stuId) {
        await this.$http.put(`students/${this.student._id}`, {
          student: this.student,
        });
      } else {
        if (
          this.studentList.find((item: any) => item.stuId == this.student.stuId)
        ) {
          throw Error("学号重复");
        }
        await this.$http.post("students", {
          student: this.student,
        });
      }
      this.initStu();
      this.$router.push("/students/list");
      this.$message.success("保存成功");
    } catch (e) {
      this.$message.error(e.message);
    }
  }

  async fetch() {
    this.student = (await this.$http.get(`students/${this.stuId}`)).data;
  }
}
</script>
